<?php
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/8/21 14:20
 */

namespace App\Service\User;


use App\Constants\System\SysStatusConst;
use App\Constants\User\UserCategoryTypeConst;
use App\Dao\Users\UserCategoryDao;
use App\Exception\ServiceException;
use App\Model\Users\UserCategory;
use App\Utils\AmountUtils;
use Hyperf\Di\Annotation\Inject;

class UserCategoryService
{


    #[Inject]
    protected UserCategoryDao $userCategoryDao;


    /**
     * 保存用户类目
     * @param array $data
     * @return void
     */
    public function batchSave(array $data)
    {
        $saveData = [];
        $userInfo = auth()->user();
        if(!empty($data['income']))
        {
            foreach($data['income'] as $item)
            {
                if(!empty($item['name']))
                {
                    $saveData[] = [
                        'uid' => $userInfo->getId(),
                        'industry_id' => $data['industry_id'],
                        'name' => $item['name'],
                        'icon' => $item['icon'] ?? '',
                        'price' => $item['price'] ?? 0,
                        'commission_rate' => !empty($item['percent']) ? AmountUtils::fenToYuan($item['percent']): 0,
                        'remark' => "",
                        'type' => UserCategoryTypeConst::INCOME->value,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                }
            }
        }
        if(!empty($data['expense']))
        {
            foreach($data['expense'] as $item)
            {
                if(!empty($item['name']))
                {
                    $saveData[] = [
                        'uid' => $userInfo->getId(),
                        'industry_id' => $data['industry_id'],
                        'name' => $item['name'],
                        'icon' => $item['icon'] ?? '',
                        'price' => $item['price'] ?? 0,
                        'commission_rate' => !empty($item['percent']) ? AmountUtils::fenToYuan($item['percent']): 0,
                        'remark' => "",
                        'type' => UserCategoryTypeConst::EXPENSE->value,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                }
            }
        }
        $userInfo->industry_id = $data['industry_id'];
        $userInfo->save();
        (new UserCategory())->upsert($saveData,['uid','name','icon','industry_id','commission_rate','updated_at']);
    }

    public function removeCategory(int $id)
    {
        $userInfo = auth()->user();

        $userCategoryInfo = $this->userCategoryDao->getCateById($id);

        if(!$userCategoryInfo || $userCategoryInfo->uid != $userInfo->getId())
        {
            throw new ServiceException("类目不存在");
        }

        $userCategoryInfo->is_del = SysStatusConst::DELETE->value;

        $res = $userCategoryInfo->save();

        if(!$res) throw new ServiceException("删除失败");


    }

    /**
     * 保存用户类目
     * @param array $data
     * @return void
     */
    public function saveCategory(array $data)
    {
        $userInfo = auth()->user();
        if(!empty($data['id']))
        {
            $userCategory = UserCategory::query()->where('id','=',$data['id'])->where('uid','=',$userInfo->getId())->first();
        }else{
            $data['uid'] = $userInfo->getId();
            $userCategory = new UserCategory();
        }
        if(empty($data['industry_id']))
        {
            $data['industry_id'] = $userInfo->industry_id;
        }
        if(!empty($data))
        {
            $data['commission_rate'] = AmountUtils::fenToYuan($data['commission_rate']);
        }
        $res = $userCategory->fill($data)->save();
        if(!$res) throw new ServiceException("更新失败");

    }

    public function categoryData(int|null $type = null)
    {
        $userInfo = auth()->user();


        $isSub = UserService::isSubAccount($userInfo);
        $paramsUid = $userInfo->getId();
        if($isSub)
        {
            $paramsUid = $userInfo->soft_id;
        }
        $userCategory = UserCategory::query()
            ->select(['id','name','icon','price','commission_rate','type','remark','industry_id'])
            ->where('uid','=',$paramsUid)->where('is_del','=',SysStatusConst::NORMAL->value);

        if(!empty($type))
        {
            $userCategory->where('type','=',$type);
        }
        $categoeryData = $userCategory->get()->toArray();

        foreach($categoeryData as &$item)
        {
            $item['commission_rate'] = AmountUtils::yuanTofen($item['commission_rate']);
        }
        return $categoeryData;
    }
}